package v1

import (
	"code.oldboyedu.com/studygo/ginStsMgr/common"
	"code.oldboyedu.com/studygo/ginStsMgr/dao/teacher"
	"code.oldboyedu.com/studygo/ginStsMgr/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

/*
	实现老师的增删改查
*/
func CreateTea(c *gin.Context) {
	var data model.Teacher
	err := c.ShouldBind(&data)
	if err != nil {
		fmt.Println("绑定参数失败", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"status": common.BindERROR,
			"msg":    common.GetCode(common.BindERROR),
		})
		return
	}
	code := teacher.CheckName(data.Name)
	if code == common.SUCCESS {
		teacher.CreateTeacher(&data)
	}
	if code == common.TeaNameExist {
		code = common.TeaNameExist
	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    common.GetCode(code),
	})
}
func ViewSTId(c *gin.Context) {
	var data model.Teacher
	id, _ := strconv.Atoi(c.Param("id"))
	code := teacher.CheckId(id, &data)
	if code == common.SUCCESS {
		teacher.ViewSTId(id, &data)
	}
	if code == common.ERROR {
		code = common.ViesTeaIDFailed
	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    common.GetCode(code),
		"data":   data,
	})
}
func ViewST(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))
	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageNum == 0 {
		pageNum = 1
	}
	data, code := teacher.ViewST(pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    common.GetCode(code),
	})
}
func DelST(c *gin.Context) {
	var data model.Teacher
	id, _ := strconv.Atoi(c.Param("id"))
	code := teacher.CheckId(id, &data)
	if code == common.SUCCESS {
		teacher.DelST(id, &data)
	}
	if code == common.ERROR {
		code = common.DelTeaFailed
	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    common.GetCode(code),
	})
}
func UpdateST(c *gin.Context) {
	var data model.Teacher
	id, _ := strconv.Atoi(c.Param("id"))
	err := c.ShouldBindJSON(&data)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": common.BindERROR,
			"msg":    common.GetCode(common.BindERROR),
		})
		return
	}
	code := teacher.CheckName(data.Name)
	if code == common.SUCCESS {
		teacher.Update(id, &data)
	}
	if code == common.TeaNameExist {
		code = common.ERROR
	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    common.GetCode(code),
		"data":   data,
	})
}
